//
//  WJOAuthViewController.swift
//  WJWeibo
//
//  Created by Jie on 15/12/20.
//  Copyright © 2015年 周文杰. All rights reserved.
//

import UIKit
import SVProgressHUD

class WJOAuthViewController: UIViewController , UIWebViewDelegate{

    lazy var webView = UIWebView()
    override func viewDidLoad() {
        super.viewDidLoad()

        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        
        navigationItem.title = "登陆"
        
        let request = NSURLRequest(URL: NetworkTools.shadredInstance.oauthUrl())
        webView.loadRequest(request)
    }


    override func loadView() {
        view = webView
        webView.delegate = self
    }
    

    ///关闭
    func close() {
        
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true) { () -> Void in
        }
    }
    
    /// 填充账号密码
    func autoFill() {
        // 创建js代码
        let js = "document.getElementById('userId').value='huahua384167@163.com'; document.getElementById('passwd').value='Tt384167';"
        
        // 让webView来执行js代码
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    
    ///加载AccessToken
    func loadAccessToken(code: String) {
        NetworkTools.shadredInstance.loadAccessToken(code) { (result, error) -> () in
            //判断网络请求是否有错误
            if error != nil {
                print("error:\(error)")
                
                SVProgressHUD.showInfoWithStatus("你的网络不给力")
                //延迟
                dispatch_after(10, dispatch_get_main_queue(), { () -> Void in
                    
                    self.close()
                    
                })
                return
            }
            //print("\(result)")
            //保存AccessToken
            //字典转模型
            let userAccount = WJUserAccount(dict: result!)
            //保存到沙盒
            
            userAccount.saveUserAccount()
            
            
        }
    }
    
    //MARK: - webView代理方法
    ///检测到要加载url的时候会调用该方法，拦截url
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlString = request.URL!.absoluteString
        // 如果加载的不是授权回调页面,直接加载网页,
        // 如果加载的是授权回调页面,对后面的参数进行判断,如果有code=表示点击了授权按钮,否则点击取消
        if !urlString.hasPrefix(NetworkTools.shadredInstance.redirect_uri) {
            return true
        }
        //判断后面有没有参数
        if let query = request.URL?.query {
            let nsQuery = query as NSString
            let codeString = "code="
            //hasPrefix 判断包含有没有这个字符串
            if nsQuery.hasPrefix(codeString) {
                //获得code
                let code = nsQuery.substringFromIndex(codeString.characters.count)
                
                //获得AccessToken
                loadAccessToken(code)
                
            }else{
                close()
            }
        }else{
            print("query没有值")
        }
        return false
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }




}
